/*
 * @Description: 数据适配方法
 * @version:
 * @Author: E-CHOOSEUS R&D
 * @LastEditors: E-CHOOSEUS R&D
 */

import { format } from 'date-fns'
import { cloneDeep } from 'lodash-unified'
import { nanoid } from 'nanoid'

/**
 * @description 扁平化 后台返回的渲染数据信息
 * @param {*} list
 */
export function toFlatData(list, otherInfo = { name: '' }) {
  /* ------------------------------------------------------------------------------------------------------------------ */
  /*                                                      第一步: 提取数据                                                     */
  /* ------------------------------------------------------------------------------------------------------------------ */
  const fList1 = [] // * 数据拍平数组一
  list = cloneDeep(list) // 拷贝一份副本
  const cType1Reg = /#$/ // 正则匹配表达式
  /**
   * @description 判断数据是否为班次汇总类型
   * @param {*} str
   * @param {*} regExp
   * @returns
   */
  const parseTimeFormat = (str = '', regExp = cType1Reg) => {
    const isMatched = regExp.test(str)
    const result = {
      t: str,
      cType: 0
    }
    if (isMatched) {
      result.t = str.substring(0, str.length - 1)
      result.cType = 1
    }
    // const tSplitArr = str.split(':')
    // // ? 删除多余的秒字符串
    // if (tSplitArr.length === 3) {
    //   result.t = tSplitArr[0] + ':' + tSplitArr[1]
    // }
    result.t = str.split('@')[0]
    return result
  }

  for (let i = 0, len = list.length; i < len; ++i) {
    const item = list[i]
    const fItem = {
      timestamp: null, // 时间戳
      t: null, // 时间字符串
      data: [], // 数据列表
      cType: 0, // 内容类型 0: 默认, 1: 班次汇总
      username: otherInfo.name // 登录者名称
    }
    for (const t in item) {
      if (Object.hasOwnProperty.call(item, t)) {
        const tData = item[t]
        fItem.timestamp = t
        fItem.t = t
        fItem.cType = cType1Reg.test(t)
        fItem.data = tData

        const timeInfo = parseTimeFormat(t)
        fItem.t = timeInfo.t
        fItem.cType = timeInfo.cType
      }
    }
    fList1.push(fItem)
  }

  return fList1

  /* ------------------------------------------------------------------------------------------------------------------ */
  /*                                                     第二步: 组合对象的键                                                    */
  /* ------------------------------------------------------------------------------------------------------------------ */

  /* const fList2 = []; // 组合数据列表到属性上
  for (let i = 0, len = fList1.length; i < len; i++) {
    const item = [i];
    const fItem2 = {
      ...cloneDeep(item)
    };
  } */
}

/**
 * @description 获取记录数据不存在时的单元格空对象
 * @param {*} dictType
 * @param {*} row
 * @returns
 */
function parseToCellData(dictType, row) {
  const result = {
    _uuid: row._uuid, // 指向的配置列 uuid
    dictValue: dictType, // 保留所属分类标识
    val: '', // 展示的值
    width: row._width || 'unset', // 宽度同头部配置列 _width
    splicer: row.splicer
  }
  //   日期时间类型
  if (dictType === 'date_value') {
    result['dateType'] = row.dateType
    return result
  }
  //   护理记录类型
  //   todo 未看到相关的数据格式
  if (dictType === 'yx-hljl') {
    result['hljl-careContent'] = null
    return result
  }

  //   评估评分类型
  if (dictType === 'yx-pgpf') {
    result['pgpf-type'] = row.pgType || null
    result['pgpf-pgId'] = row.pgId || null
    result['pgpf-showValue'] = null
    return result
  }

  //   出入量类型
  if (dictType === 'yx-crl') {
    result['crl-modelCode'] = row.modelType
    result['crl-itemCode'] = row.itemCode || null
    result['crl-ioValue'] = null
    return result
  }

  //   操作人员类型 值为当前登录的用户名
  if (dictType === 'operater') {
    result['sign-fieldCode'] = 'operater'
    result['sign-fieldValue'] = null
    return result
  }

  //    护理操作类型
  if (dictType === 'yx-hlcz') {
    result['hlcz-itemCode'] = row.itemCode || null
    result['hlcz-itemValue'] = null
    return result
  }

  // 护理评估
  if (dictType === 'yx-hlgc') {
    result['hlgc-fieldCode'] = row.obsvCode || null
    result['hlgc-fieldValue'] = null
    return result
  }

  // 特殊药物
  if (dictType === 'yx-yzzxjl') {
    result['dataCode'] = row.dataCode || null
    result['yzzxjl-fieldCode'] = row.itemCode || null
    result['yzzxjl-fieldValue'] = null
    return result
  }

  // 约束记录
  if (dictType === 'yx-ysjl') {
    result['dataCode'] = row.dataCode || null
    result['ysjl-fieldCode'] = row.itemCode || null
    result['ysjl-fieldValue'] = null
    return result
  }

  // 病情观察
  if (dictType === 'yx-bqgc') {
    result['bqgc-fieldCode'] = row.itemCode || null
    result['bqgc-fieldValue'] = null
    return result
  }

  // 自定义文本
  if (dictType === 'yx-diy') {
    result['diy-fieldCode'] = row.itemCode || null
    result['diy-fieldValue'] = null
    return result
  }

  //   观察项类型
  if (dictType === 'yx-gcx' || dictType === 'yx-diy') {
    result['enumMap'] = row.enumMap
    result['gcx-obsvCode'] = row.obsvCode || null
    result['gcx-propValue'] = null

    // * 处理观察项 枚举类型, 且非结构体内观察项
    if (row.obsvDataType === 'enum' && row._isLeaf) {
      const enumMap = {} // 枚举类型选项map
      const enumList = row.jgtChild || []
      for (const eItem of enumList) {
        enumMap[eItem.obsvCode] = eItem.obsvName
      }

      result._obsvDataType = row.obsvDataType
      result._enumMap = enumMap
    }
    // * 处理观察项结构体下枚举类型
    if (row.dataType === 'enum' && row.dataDefine && row._isLeaf) {
      const enumMap = {} // 枚举类型选项map
      const options = []
      for (const _ of row.dataDefine) {
        options.push(_)
      }

      for (const option of options) {
        enumMap[option.obsvCode] = option.obsvName
      }

      result._obsvDataType = row.dataType
      result._enumMap = enumMap
    }
    return result
  }

  return result
}

/**
 * @description 获取没有数据时的空行渲染列表
 * @param {*} tree
 * @returns
 */
export function getRenderRowDefault(tree) {
  const list = []
  // 遍历外层
  for (let i = 0, iLen = tree.length; i < iLen; ++i) {
    const l1Node = tree[i]
    const l1ChildList = l1Node.childNode || []

    // ? 子节点长度为 0 直接投入
    if (!l1ChildList.length) {
      const item = parseToCellData(l1Node.dictValue, l1Node)
      list.push(item)
      continue
    }

    for (let j = 0, jLen = l1ChildList.length; j < jLen; ++j) {
      const l2Node = l1ChildList[j]

      // * 非观察项, 且同时不是结构体类型
      // if (!(l1Node.dictValue === "yx-gcx" && l2Node.obsvDataType === "struct")) {
      //   const item = parseToCellData(l1Node.dictValue, l2Node);
      //   list.push(item);
      //   continue;
      // }

      // ! 结构体子项可能为空
      const jgtChild = l2Node.childNode || []
      if (!jgtChild.length) {
        const item = parseToCellData(l2Node.dictValue, l2Node)
        list.push(item)
        continue
      }
      // * 处理观察项结构体
      for (let k = 0, kLen = jgtChild.length; k < kLen; ++k) {
        const jgtNode = jgtChild[k]
        const item = parseToCellData(jgtNode.dictValue, jgtNode)
        list.push(item)
      }
    }
  }
  return list
}

// ? 重症护理单配置分类
const IcrDictType = {
  'yx-pgpf': 'yx-pgpf',
  'yx-gcx': 'yx-gcx',
  'yx-hlgc': 'yx-hlgc',
  'yx-yzzxjl': 'yx-yzzxjl',
  'yx-ysjl': 'yx-ysjl',
  'yx-bqgc': 'yx-bqgc',
  'yx-crl': 'yx-crl',
  'yx-hljl': 'yx-hljl',
  'yx-hlcz': 'yx-hlcz',
  date_value: 'date_value',
  operater: 'operater',
  'yx-crl-in': 'yx-crl-in', // ? 新增固定列 ”入量“
  'yx-crl-out': 'yx-crl-out', // ? 新增固定列 ”出量“
  'yx-diy': 'yx-diy', // ? 新增固定列 ”自定义文本“
  unknown: 'unknown'
}

// 不同类型匹配的键
export const matchKeys = {
  [IcrDictType['yx-pgpf']]: 'pgpf-pgId',
  [IcrDictType['yx-gcx']]: 'gcx-obsvCode',
  [IcrDictType['yx-diy']]: 'diy-fieldCode',
  [IcrDictType['yx-hlgc']]: 'hlgc-fieldCode',
  [IcrDictType['yx-yzzxjl']]: 'yzzxjl-fieldCode',
  [IcrDictType['yx-ysjl']]: 'ysjl-fieldCode',
  [IcrDictType['yx-bqgc']]: 'bqgc-fieldCode',
  [IcrDictType['yx-crl']]: 'crl-modelCode,crl-itemCode',
  [IcrDictType['yx-hlcz']]: 'hlcz-itemCode',
  [IcrDictType['yx-hljl']]: '',
  [IcrDictType['yx-crl-in']]: IcrDictType['yx-crl-in'] + '-name',
  [IcrDictType['yx-crl-out']]: IcrDictType['yx-crl-out'] + '-name',
  [IcrDictType['operater']]: 'sign-fieldCode'
}
// 不同类型储值的键
export const matchValKeys = {
  [IcrDictType['yx-pgpf']]: 'pgpf-showValue',
  [IcrDictType['yx-gcx']]: 'gcx-propValue',
  [IcrDictType['yx-diy']]: 'diy-fieldValue',
  [IcrDictType['yx-hlgc']]: 'hlgc-fieldValue',
  [IcrDictType['yx-yzzxjl']]: 'yzzxjl-fieldValue',
  [IcrDictType['yx-ysjl']]: 'ysjl-fieldValue',
  [IcrDictType['yx-bqgc']]: 'bqgc-fieldValue',
  [IcrDictType['yx-crl']]: 'crl-ioValue',
  [IcrDictType['yx-hlcz']]: 'hlcz-itemValue',
  [IcrDictType['yx-hljl']]: 'hljl-careContent',
  [IcrDictType['yx-crl-in']]: IcrDictType['yx-crl-in'] + '-value',
  [IcrDictType['yx-crl-out']]: IcrDictType['yx-crl-out'] + '-value',
  [IcrDictType['operater']]: 'sign-fieldValue'
}
const matchRecordIdKeys = {
  [IcrDictType['yx-gcx']]: 'gcx-recordId',
  [IcrDictType['yx-diy']]: 'diy-fieldValue',
  [IcrDictType['yx-hlgc']]: 'hlgc-recordId',
  [IcrDictType['yx-yzzxjl']]: 'yzzxjl-recordId',
  [IcrDictType['yx-ysjl']]: 'ysjl-recordId',
  [IcrDictType['yx-bqgc']]: 'bqgc-recordId',
  [IcrDictType['yx-pgpf']]: 'pgpf-recordId',
  [IcrDictType['yx-hlcz']]: 'hlcz-recordId',
  [IcrDictType['yx-hljl']]: 'hljl-recordId',
  [IcrDictType['yx-crl-in']]: 'crl-recordId',
  [IcrDictType['yx-crl-out']]: 'crl-recordId',
  [IcrDictType['operater']]: 'sign-recordId'
}

const hlczMap = {
  care_qnyjc: 'A',
  care_xt: 'B',
  care_pb: 'C',
  care_kqhl: 'D',
  care_hyhl: 'E',
  care_whxr: 'F',
  care_gc: 'G',
  care_zdks: 'H',
  care_ww: 'I',
  care_zdpt: 'J',
  care_cs: 'K',
  care_ghyld: 'L',
  care_pfhl: 'M',
  care_qqhl: 'N',
  care_xtou: 'O',
  care_tx: 'P',
  care_jzj: 'Q'
}

/**
 * @description 表格渲染行对象 从数据列中匹配值
 * @param {*} srcList 表格渲染 行列表
 * @param {*} valObj 做了基本拍平的 行结果集合对象
 * @returns
 */
export function getValFilledRow(srcList, valObj) {
  const valList = valObj.data || []
  // console.log(cloneDeep(srcList), cloneDeep(valObj))

  /**
   * @description 比较两个对象的键值是否相等
   * @param {*} left
   * @param {*} right
   * @param {*} props
   * @returns
   */
  const isPropsMatch = (left = {}, right = {}, props) => {
    props = props.split(',')
    const hasNullVal = props.some(
      prop => right[prop] === null || right[prop] === undefined
    ) // ? 右侧对象比对属性存在 null 或 undefined, 直接认定不符合
    return hasNullVal
      ? false
      : props.every(prop => {
          return prop && left[prop] && right[prop] && left[prop] == right[prop]
        })
  }
  // console.log(srcList)
  // ! 储值数据集合可能有多余, 此处不建议过早优化
  for (let i = 0, len = srcList.length; i < len; ++i) {
    const srcItem = srcList[i]
    // console.log(cloneDeep(srcItem))
    // ? 处理时间日期
    if (srcItem.dictValue === IcrDictType.date_value) {
      let date
      if (valObj.t) {
        date = valObj.t.split('@')[0]
      } else {
        date = valObj.t
      }
      srcItem.val = date
      continue
    }
    // // ? 处理操作人员
    // if (srcItem.dictValue === IcrDictType.operater) {
    //   if (Array.isArray(valList)) {
    //     const myarray = valList
    //       .filter(item => item['create-time'])
    //       .sort((a, b) => b['create-time'] - a['create-time'])
    //     if (myarray.length > 0) {
    //       srcItem.val = myarray[0].operator
    //     } else {
    //       const valListItem = valList.find(item => {
    //         return item.operator
    //       })
    //       srcItem.val = valListItem ? valListItem.operator : ''
    //     }
    //   } else {
    //     // srcItem.val = valObj.username;
    //     srcItem.val = ''
    //   }
    //   continue
    // }
    if (srcItem.dictValue === IcrDictType.unknown) {
      // console.log("srcItem valList, i: ", srcItem, valList, i);
      let str = ''
      for (const valItem of valList) {
        for (const key in valItem) {
          if (Object.hasOwnProperty.call(valItem, key) && key !== 'operator') {
            const keyVal = valItem[key]
            str += keyVal
          }
        }
      }
      srcItem.val = str
      continue
    }

    if (
      [
        IcrDictType['yx-gcx'],
        IcrDictType['yx-hlgc'],
        IcrDictType['yx-yzzxjl'],
        IcrDictType['yx-ysjl'],
        IcrDictType['yx-bqgc'],
        IcrDictType['yx-pgpf'],
        IcrDictType['yx-hlcz'],
        IcrDictType['yx-crl'],
        IcrDictType['yx-hljl'],
        IcrDictType['yx-crl-in'],
        IcrDictType['yx-crl-out'],
        IcrDictType['operater'],
        IcrDictType['yx-diy']
      ].includes(srcItem.dictValue)
    ) {
      const matchKey = matchKeys[srcItem.dictValue] // 数据匹配键
      const matchRecordIdKey = matchRecordIdKeys[srcItem.dictValue]
      // console.log(matchKey)

      for (let j = 0, jLen = valList.length; j < jLen; ++j) {
        const valItem = valList[j] // 数据记录

        const matchValKey = matchValKeys[srcItem.dictValue] // 数据存储值 键名
        // ! 护理记录和病情观察有值直接取, 没有所谓匹配键
        if (
          (srcItem.dictValue === IcrDictType['yx-hljl'] ||
            srcItem.dictValue === IcrDictType['yx-bqgc']) &&
          valItem[matchValKey] !== null &&
          valItem[matchValKey] !== undefined
        ) {
          const val = valItem[matchValKey]

          srcItem.val = val
          srcItem[matchValKey] = val
          srcItem.id = valItem[matchRecordIdKey]
          continue
        }

        const addCrlExtraField = () => {
          const id =
            srcItem.dictValue === IcrDictType['yx-crl-in']
              ? valItem['yx-crl-in-id']
              : valItem['yx-crl-out-id']
          srcItem.id = srcItem.id || ''
          srcItem.id && (srcItem.id += ';')
          srcItem.id += id
          srcItem.itemCode = srcItem.itemCode || ''
          srcItem.itemCode && (srcItem.itemCode += ';')
          srcItem.itemCode += valItem['item-code']
          srcItem.masterId = srcItem.masterId || ''
          srcItem.masterId && (srcItem.masterId += ';')
          srcItem.masterId += valItem['yx-crl-in-yao-master-id']
          srcItem.source = srcItem.source || ''
          srcItem.source && (srcItem.source += ';')
          srcItem.source += valItem[srcItem.dictValue + '-source']
        }

        if (
          (srcItem.dictValue === IcrDictType['yx-crl-in'] &&
            valItem[matchKey] !== null &&
            valItem[matchKey] !== void 0) ||
          (srcItem.dictValue === IcrDictType['yx-crl-out'] &&
            valItem[matchKey] !== null &&
            valItem[matchKey] !== void 0)
        ) {
          /* console.log(
            "matchKey, matchValKey, valItem[matchKey], valItem[matchValKey]: ",
            matchKey,
            matchValKey,
            valItem[matchKey],
            valItem[matchValKey]
          ); */
          // srcItem.val && (srcItem.val += ';')
          // if (srcItem.dictValue === IcrDictType['yx-crl-out']) {
          //   srcItem.val +=
          //     valItem[matchKey] +
          //     ' ' +
          //     (valItem['yx-crl-out-nature'] || '') +
          //     ' ' +
          //     valItem[matchValKey]
          // } else {
          //   srcItem.val += valItem[matchKey] + ' ' + valItem[matchValKey]
          // }
          // addCrlExtraField()
          srcItem.val = valItem[matchValKey]
          srcItem.id = valItem[matchRecordIdKey]
          continue
        }

        // ? 特殊处理固定列, 入量模块的相关执行用药信息的获取
        const yxCrlInExecDrugKeySuffix = '-yao-name' // * 固定列 "入量" 关联执行用药键名后缀
        const matchRelativeKey =
          IcrDictType['yx-crl-in'] + yxCrlInExecDrugKeySuffix
        if (
          srcItem.dictValue === IcrDictType['yx-crl-in'] &&
          valItem[matchRelativeKey] !== null &&
          valItem[matchRelativeKey] !== void 0
        ) {
          srcItem.val && (srcItem.val += ';')
          srcItem.val += valItem[matchRelativeKey]
          addCrlExtraField()
          continue
        }

        // ? 处理评估评分疼痛
        if (
          srcItem.dictValue === IcrDictType['yx-pgpf'] &&
          srcItem['pgpf-type'] &&
          srcItem['pgpf-type'].length > 0
        ) {
          if (srcItem['pgpf-type'].includes(valItem['pgpf-type'])) {
            const val = valItem[matchValKey]
            if (val !== undefined && val !== null) {
              if (!srcItem.val) {
                // srcItem.val = "";
                srcItem.val = val
                srcItem.id = valItem['pgpf-recordId']
              } else {
                const codeIndex = srcItem[matchKey].findIndex(
                  item => item === valItem[matchKey]
                )
                const splicer = srcItem.splicer || ''
                const myarr = srcItem.val.split(splicer)
                myarr.splice(codeIndex, 0, val)
                srcItem.val = myarr.join(splicer)
                // srcItem.val += srcItem.splicer || "";
              }
              // srcItem.val += val;
            }
          }
          continue
        }

        // * 匹配的条件相等, 才赋值
        if (isPropsMatch(srcItem, valItem, matchKey)) {
          // * 观察项枚举类型
          if (
            srcItem.dictValue === IcrDictType['yx-gcx'] &&
            srcItem.enumMap &&
            srcItem._obsvDataType === 'enum'
          ) {
            const enumMapItem = srcItem['enumMap'][valItem[matchKey]]
            if (enumMapItem) {
              const val =
                srcItem['enumMap'][valItem[matchKey]][valItem[matchValKey]]
              if (val) {
                if (!srcItem.val) {
                  // srcItem.val = "";
                  srcItem.val = val
                  srcItem.id = valItem[matchRecordIdKey]
                } else {
                  const codeIndex = srcItem[matchKey].findIndex(
                    item => item === valItem[matchKey]
                  )
                  const splicer = srcItem.splicer || ''
                  const myarr = srcItem.val.split(splicer)
                  myarr.splice(codeIndex, 0, val)
                  srcItem.val = myarr.join(splicer)
                  // srcItem.val += srcItem.splicer || "";
                }
                // srcItem.val += val;
              }
            }
          }
          // 处理平均压，有创和无创优先取有创
          else if (
            srcItem.dictValue === IcrDictType['yx-gcx'] &&
            (valItem[matchKey] === 'ibpM' || valItem[matchKey] === 'nIbpM')
          ) {
            if (valItem[matchKey] === 'ibpM') {
              srcItem.val = valItem[matchValKey]
              srcItem.id = valItem[matchRecordIdKey]
            } else if (valItem[matchKey] === 'nIbpM' && !srcItem.val) {
              srcItem.val = valItem[matchValKey]
              srcItem.id = valItem[matchRecordIdKey]
            }
          } else {
            let val = valItem[matchValKey] // 读取值
            // 处理护理操作数据
            if (srcItem.dictValue === IcrDictType['yx-hlcz']) {
              val = val || ''
            }

            if (val !== undefined && val !== null) {
              if (!srcItem.val) {
                // console.log(val, valItem[matchRecordIdKey])
                srcItem.val = val
                // console.log(valItem)
                srcItem.id = valItem[matchRecordIdKey]
              } else {
                // 当一个时间点有多条签名数据的时候取第一条，后面的签名数据不处理
                if (Array.isArray(srcItem[matchKey])) {
                  const codeIndex = srcItem[matchKey].findIndex(
                    item => item === valItem[matchKey]
                  )
                  const splicer = srcItem.splicer || ''
                  const myarr = srcItem.val.split(splicer)
                  const myIds = srcItem.id ? srcItem.id.split(splicer) : []
                  if (srcItem[matchKey].length > 1) {
                    myarr.splice(codeIndex, 0, val)
                    myIds.splice(codeIndex, 0, valItem[matchRecordIdKey])
                  } else {
                    myarr.push(val)
                    myIds.push(valItem[matchRecordIdKey])
                  }
                  srcItem.val = myarr.join(splicer)
                  srcItem.id = myIds.join(splicer)
                } else {
                  srcItem.val += srcItem[matchKey]
                }
              }
              srcItem[matchValKey] = srcItem.val
            }
          }
        }
      }
    }
  }
  // console.log('srcList', srcList)
  return srcList
}

/**
 * @description 处理表格行数数据横向分页
 * @param {*} pagesColumn 横向分页表头
 * @param {*} tableList 完整的表格数据列表
 */
export function getPagesXRenderList(
  pagesColumn,
  tableList,
  pagesInfo = [],
  pagesStretchW = []
) {
  const pagesXTableList = []
  for (let i = 0, len = pagesColumn.length; i < len; ++i) {
    const columns = pagesColumn[i]
    const curPageStretchW = pagesStretchW[i]

    const xData = []
    for (let k = 0, kLen = tableList.length; k < kLen; ++k) {
      const tableRow = tableList[k]

      const pageXRowData = [] // 横向分页数据列表行
      for (let j = 0, jLen = columns.length; j < jLen; ++j) {
        const column = columns[j]
        // 出入量总计特殊处理
        if (tableRow.isSummary) {
          break
        }
        const rawDataRowList = tableRow.rData // 原始列表行
        for (let n = 0, nlLen = rawDataRowList.length; n < nlLen; ++n) {
          const item = rawDataRowList[n]
          if (item._uuid === column._uuid) {
            pageXRowData.push(cloneDeep(item))
            break
          }
        }
      }
      // * 特殊处理班次总结
      const cType = tableRow.rowType
      const onlyOperaterAndDate = columns.every(
        item =>
          item.dictValue === IcrDictType.operater ||
          item.dictValue === IcrDictType.date_value
      )
      if (cType === 1 && (!onlyOperaterAndDate || len == 1 || i < len - 1)) {
        // 当只有时间和操作人两列的时候，横向分页数大于1，横向分页最后一页不推入班次总结
        const curPageWidth = pagesInfo[i] ? pagesInfo[i].pageXWidth : 0
        for (const dItem of tableRow.rData) {
          if (dItem._noHead) {
            let spliceIndex = pageXRowData.length
            const operaterTempIndex = pageXRowData.findIndex(
              item => item.dictValue === IcrDictType.operater
            )
            const operaterTemp = pageXRowData[operaterTempIndex]
            if (operaterTemp) {
              spliceIndex = operaterTempIndex
            }
            pageXRowData.splice(
              spliceIndex,
              0,
              Object.assign(cloneDeep(dItem), {
                val: i === 0 ? dItem.val : '',
                width:
                  curPageWidth -
                  dItem._paddingW -
                  (operaterTemp ? operaterTemp.width : 0) +
                  (curPageStretchW.w || 0)
              })
            )
          }
        }
      }
      // 出入量总计特殊处理
      if (tableRow.isSummary) {
        tableRow.height = 26
      }

      const pageXRow = {
        rowType: tableRow.rowType,
        height: tableRow.height,
        rData: pageXRowData
      }
      // 出入量总计特殊处理
      if (tableRow.isSummary) {
        Object.assign(pageXRow, tableRow)
      }

      xData.push(pageXRow)
    }
    pagesXTableList.push(xData)
  }

  return pagesXTableList
}

/**
 * @description 获得每一页分页渲染数据
 * @param {*} pagesXData 横向分页数据列表
 * @param {*} pagesYSettings 纵向分页计算信息
 * @returns
 */
export function getPagingDataList(pagesXData, pagesYSettings) {
  const list = []
  for (const pageXData of pagesXData) {
    const pageYDataList = [] // 垂直列
    for (const pageSetting of pagesYSettings) {
      const { startAt, endAt } = pageSetting
      const dataList = cloneDeep(pageXData.slice(startAt, endAt + 1))
      pageYDataList.push(dataList)
    }
    list.push(pageYDataList)
  }

  return list
}

/**
 * @description 获取每页的分页数据, 包括表头和和渲染数据行
 * @param {*} pagesColumn
 * @param {*} pagesDataList
 * @param {*} fixedPagesColumnWidth // todo 该参数已过时, 应尽快移除
 * @param {*} pagesFixedColumnWidth
 * @returns
 */
export function getPagesColumnAndRData(
  pagesColumn,
  pagesDataList,
  fixedPagesColumnWidth,
  pagesFixedColumnWidth,
  pagesStretchW
) {
  const pagesList = []

  const pagesXList = []

  const walkColumnsTree = (nodeList, map) => {
    for (const iNode of nodeList) {
      iNode.stretchW = 0
      const iFixedObj = map.get(iNode._uuid)
      if (iFixedObj && iFixedObj._stretchW) {
        iNode.stretchW += iFixedObj._stretchW
      }
      const childList = iNode.childList || []
      walkColumnsTree(childList, map)
    }
  }

  // console.log("pagesFixedColumnWidth: ", pagesFixedColumnWidth);
  let verticalLen = 0 // 垂直分页数
  for (let x = 0, xLen = pagesColumn.length; x < xLen; ++x) {
    const pageColumn = pagesColumn[x]
    // console.log('pageColumn: ', pageColumn)
    const pageStretchW = pagesStretchW[x] // 当前x方向分页表格拉伸的长度

    const fixColumnsMap = new Map()
    // const pageColumnsWidth = fixedPagesColumnWidth[x];
    const pageColumnsWFixed = pagesFixedColumnWidth[x]
    const fillWidthObj = {}
    for (const columnWFixed of pageColumnsWFixed) {
      for (const key of Object.keys(columnWFixed)) {
        fillWidthObj[key] = columnWFixed[key]
        fixColumnsMap.set(key, { ...columnWFixed[key] })
      }
    }

    // * 拓展表头列的宽度
    walkColumnsTree(pageColumn, fixColumnsMap)

    // TODO 已废弃的对象, 待移除
    const fixedWidthObj = {}
    // for (const colWidth of pageColumnsWidth) {
    //   Object.keys(colWidth).map(key => {
    //     fixedWidthObj[key] = colWidth[key];
    //     return key;
    //   });
    // }

    const columnList = []

    const pagesNoXDataList = pagesDataList[x] // 每一列分页列表
    verticalLen = pagesNoXDataList.length
    for (let y = 0, yLen = pagesNoXDataList.length; y < yLen; ++y) {
      const pageYList = pagesNoXDataList[y] // 一页的数据

      // 修正班次总结宽度
      let operater_uuid
      for (let w = 0; w < pageYList.length; w++) {
        if (operater_uuid) {
          break
        }
        for (let c = 0; c < pageYList[w].rData.length; c++) {
          if (pageYList[w].rData[c].dictValue === IcrDictType.operater) {
            operater_uuid = pageYList[w].rData[c]._uuid
            break
          }
        }
      }
      pageYList.forEach(item => {
        item.rData.forEach(item2 => {
          if (item2.dictValue === IcrDictType.unknown) {
            if (fillWidthObj[operater_uuid]) {
              item2.width = item2.width - fillWidthObj[operater_uuid]._stretchW
            }
          }
        })
      })
      //

      const configItem = {
        titleColumns: cloneDeep(pageColumn),
        rData: cloneDeep(pageYList),
        x: x + 1,
        y: y + 1,
        _fixedW: fixedWidthObj, // 修正用的 cell 宽度
        _filledW: fillWidthObj, // 宽度补充
        pageStretchW: pageStretchW.w || 0 // 拉伸表格用
      }
      columnList.push(configItem)
    }
    pagesXList.push(columnList)
  }

  // * 将 pagesXList 列表拍平, 并按先横后竖的方位推入列表
  let i = 0
  while (i < verticalLen) {
    const rowList = []
    for (let j = 0; j < pagesXList.length; ++j) {
      const xList = pagesXList[j]
      rowList.push(xList[i])
    }
    const item = {
      rowList: rowList
    }
    pagesList.push(item)

    ++i
  }

  // console.log(cloneDeep(pagesList));

  return pagesList
}

/**
 * @description 分页表头格式统一
 * @param {*} pagesColumn
 * @returns
 */
export function parseTitleColumns(pagesColumn) {
  // console.log("parseTitleColumns pagesColumn: ", pagesColumn);
  const list = []
  for (const tree of pagesColumn) {
    const pList = []
    for (let i = 0, len = tree.length; i < len; ++i) {
      const l1Node = tree[i]

      const l1Item = {
        _uuid: l1Node._uuid,
        _pUuid: l1Node._pUuid,
        dictValue: l1Node.dictValue,
        isLeaf: l1Node._isLeaf,
        title: l1Node.title,
        propUnit: l1Node.propUnit,
        width: l1Node._width,
        height: l1Node._height,
        childList: [],
        fillWidth: l1Node._fillWidth,
        adjusted: l1Node._adjusted
      }
      if (l1Node._isLeaf) {
        pList.push(l1Item)
        continue
      }

      const childNodes = l1Node._childList || []
      for (let j = 0, jLen = childNodes.length; j < jLen; ++j) {
        const l2Node = childNodes[j]

        const l2Item = {
          _uuid: l2Node._uuid,
          _pUuid: l2Node._pUuid,
          dictValue: l2Node.dictValue,
          isLeaf: l2Node._isLeaf,
          title: l2Node.title,
          propUnit: l2Node.propUnit,
          width: l2Node._width,
          height: l2Node._height,
          childList: [],
          fillWidth: l2Node._fillWidth,
          adjusted: l2Node._adjusted
        }

        if (l2Node._isLeaf) {
          l1Item.childList.push(l2Item)
          continue
        }

        // if (l2Node.dictValue === IcrDictType["yx-gcx"]) {
        if (l2Node._childList && l2Node._childList.length > 0) {
          const l2ChildNodes = l2Node._childList || []

          for (let k = 0, kLen = l2ChildNodes.length; k < kLen; ++k) {
            const l3Node = l2ChildNodes[k]
            const l3Item = {
              _uuid: l3Node._uuid,
              _pUuid: l3Node._pUuid,
              dictValue: l1Node.dictValue,
              isLeaf: l3Node._isLeaf,
              title: l3Node.title,
              propUnit: l3Node.propUnit,
              width: l3Node._width,
              height: l3Node._height,
              childList: [],
              fillWidth: l3Node._fillWidth,
              adjusted: l3Node._adjusted
            }

            l2Item.childList.push(l3Item)
          }
        }

        l1Item.childList.push(l2Item)
      }

      pList.push(l1Item)
    }

    list.push(pList)
  }

  return list
}

/**
 * @description 通过数据接口返回的数据生成呼吸机数据列表
 * @param {*} renderData
 */
export function getRespList(renderData) {
  const respKeys = [
    'time',
    'config_mode',
    'config_psabove',
    'config_f',
    'pinsp',
    'o2',
    'config_peep',
    'config_vt',
    'fio2'
  ]
  const respList = {}
  renderData.forEach(v => {
    for (const key in v) {
      let f = false
      const item = v[key]
      if (!respList[key]) {
        respList[key] = {
          time: key
        }
      }
      item.forEach(v2 => {
        if (respKeys.includes(v2.dataCode)) {
          f = true
          respList[key][v2.dataCode] = v2['gcx-propValue']
        }
      })
      if (!f) {
        delete respList[key]
      }
    }
  })
  return Object.values(respList)
}
